const inquirer = require('inquirer');
const async = require('async');
const { prompts } = require('../meta/meta.js');

const extra = (err) => {
    console.log(err);
}

/**
 * 处理原始数据
 * @param {*} data 
 */
const dataSolve = (data = []) => {
    for (const name of Object.keys(prompts)) {
        data.push({ ...prompts[name], name });
    }
    return data;
}

// const meta = dataSolve();


/**
 * 收集并挂载到data上
 * 待进一步完善
 * @param {*} data 
 * @param {*} prompts 
 * @param {*} done 
 */



const prompt = (data = {}, prompts = {}, done = extra) => {
    prompts = Array.isArray(prompts) ? prompts : dataSolve();

    // inquirer.prompt(prompts).then(answers => {
    //     console.log(answers);
    //     Object.assign(data, answers);
    //     done();
    // });

    // 依次执行并获取当次问题答案, 可在每次获取答案后增加额外的业务逻辑
    async.eachSeries(prompts, (prompt, callback) => {
        if (prompt.when) {
            prompt.when = prompt.when.bind(Object.prefix);
        }

        inquirer.prompt([prompt]).then(answer => {
            Object.prefix = answer;
            // data = { ...data, ...answer };
            Object.assign(data, answer);
            callback();
        });
    }, done);

    // 皆可以在data挂载用户输入信息
}

const options = [
    {
        type: "confirm",
        message: "是否使用监听？",
        name: "watch",
        prefix: "prefix"
    },
    {
        type: "confirm",
        message: "是否进行文件过滤？",
        name: "filter",
        suffix: "suffix",
        when: function (answer) { // 当watch为true的时候才会提问当前问题
            return this.watch;
        }
    },
    {
        type: "string",
        required: true,
        name: "name",
        message: "Project name",
        default: "miniprogram"
    }];
const answers = prompt({}, options, () => { console.log("Log End") });

module.exports = prompt;